<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Cart;
use App\Good;
use Auth;

/**
*购物车对应Controller
*/

class FlowController extends Controller
{
    //验证用户是否已登录的中间件,//验证该商品是否存在的中间件
    protected $middleware = ['App\Http\Middleware\HomeValidation'=>[]];

    /**
    *购物车列表
    *
    */
    public function cartlist(){
        $uid = session('uid');

        $cart = Cart::where('uid',$uid)->leftjoin('goods','carts.gid','=','goods.gid')->get();
    	return view('flow.cart',['cart'=>$cart]);
    }

    /**
    *添加商品到购物车
    *@param int $gid 要添加到购物车的商品
    */
    public function cartadd($gid,$num=1){
        $goods = Good::find($gid);
        $uid = session('uid');

    	//查找当前用户的购物车中是否已存在该商品
    	$cart = Cart::where('uid',$uid)->where('gid',$gid)->first();
    	if(!empty($cart)){
    		$cart->num +=$num;
    		$cart->save();
            return 1;
    	}else {
    		$cart = new Cart();
	    	//能找到,则添加到购物车
	    	$cart->gid = $gid;
	    	$cart->uid = $uid;
	    	$cart-> goods_name = $goods->goods_name;
	    	$cart->price = $goods->shop_price;
	    	$cart->thumb_img = $goods->thumb_img;
	    	$cart->num = 1;
	    	$cart->addtime = time();

	    	//保存到表格,保存成功返回true，失败返回false
	    	if( !$cart->save() ){
	    		return 0;
	    	}else {
	    		return 1;
	    	}
    	}

    }

    /**
    *删除购物车中的商品
    *@param int $gid 要被删除的商品id
    */
    public function cartdel($gid){
        $uid = session('uid');
    	$res = Cart::where('uid',$uid)->where('gid',$gid)->delete();
        if(!$res){
            return 0;
        }else {
            return 1;
        }
    }

    /**
    *购物车中商品数量减一
    *@param int $gid 数量要减少的商品id
    */
    public function numdel($gid){
        $uid = session('uid');
        $cart = Cart::where('uid',$uid)->where('gid',$gid)->first();
        if($cart->num == 1){
            Cart::where('cart_id',$cart->cart_id)->delete();
        }else {
            $cart->num -= 1;
            $cart->save();
        }
    }

    /**
    *购物车中的商品数量加一
    *@param int $gid 数量要增加的商品id
    */
    public function numadd($gid){
        $uid = session('uid');
        $cart = Cart::where('uid',$uid)->where('gid',$gid)->first();
        $cart->num += 1;
        $cart->save();
    }     
}
